package com.stars.easyms.redis.interceptor;

import com.stars.easyms.redis.annotion.RedisSetAdd;
import com.stars.easyms.redis.exception.RedisInterceptorException;
import org.aopalliance.intercept.MethodInvocation;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

/**
 * <p>className: RedisSetAddInterceptor</p>
 * <p>description: RedisSetAdd注解拦截器</p>
 *
 * @author jinzhilong
 * @date 2019-12-24 17:44
 */
public class RedisSetAddInterceptor extends AbstractRedisInterceptor<RedisSetAdd> {

    @Override
    Object invoke(MethodInvocation methodInvocation, RedisSetAdd redisSetAdd) throws RedisInterceptorException {
        Object result = proceed(methodInvocation);
        if (isEnabled() && result != null) {
            String redisKey = getRedisKey(methodInvocation, redisSetAdd.group());
            Class<?> returnType = methodInvocation.getMethod().getReturnType();
            if (Collection.class.isAssignableFrom(returnType)) {
                easyMsRedisTemplate.setAdd(redisKey, (Collection) result);
            } else {
                easyMsRedisTemplate.setAdd(redisKey, result);
            }
            Long expire = getExpire(methodInvocation, redisSetAdd.expire());
            boolean isSetExpire = expire != null && expire > 0
                    && (redisSetAdd.resetExpire() || easyMsRedisTemplate.getExpire(redisKey, TimeUnit.MILLISECONDS) <= 0);
            if (isSetExpire) {
                easyMsRedisTemplate.expire(redisKey, expire, TimeUnit.MILLISECONDS);
            }
        }
        return result;
    }
}